package com.se.io;

import cn.hutool.Hutool;
import cn.hutool.core.io.FileUtil;

import java.io.*;

import static com.se.io.FileCodeTypeUtil.getFileCodeType;

public class ReadTxtFile {

    public static void main(String[] args) throws IOException {
        String filename = "D:\\a.txt";
        fileReaderForRead(filename); //不推荐,中文会有乱码
        fileInputStreamForRead(filename);
        InputStreamReaderForRead(filename); //推荐,一行一行读取


    }


    private static void fileReaderForRead(String filename) throws IOException {
/*      FileReader是默认按中文系统的GBK来编码的，然后在UTF-8 -> GBK -> UTF-8的过程中
        编码出现损失造成结果不能还原最初的字符。
        FileReader继承了InputStreamReader，但并没有实现父类中带字符集参数的构造函数。
        所以我们直接用InputStreamReader代替FileReader，
        InputStreamReader isr=new InputStreamReader(new FileInputStream(fileName),"UTF-8");
        这样读取文件就会直接用UTF-8解码，不用再做编码转换。

        - InputStreamReader是字节流转为字符流的桥梁，首先要new一个FileInputStream字节流，再在该字节流上new 一个InputStreamReader，然后BUfferedReader 缓存流必须建立在一个存在的流的基础上
        - InputStreamReader类与FileReader类关系
          1、FileReader类仅仅是InputStreamReader的简单衍生并未扩展任何功能
          2、FileReader类读取数据实质是InputStreamReader类在读取，而InputStreamReader读取数据实际是StreamDecoder类读取
          3、因此在使用字符输入流的时候实际是StreamDecoder类在发挥作用

          https://www.cnblogs.com/jpfss/p/9789390.html
 */

        FileReader reader = new FileReader(filename);
        BufferedReader buf = new BufferedReader(reader);
        String line;
        while ((line = buf.readLine()) != null) {
            System.out.println(line);
        }


    }

    private static void InputStreamReaderForRead(String filename) throws IOException {
        System.out.println(getFileCodeType(filename));
        InputStreamReader reader = new InputStreamReader(
                new FileInputStream(filename), getFileCodeType(filename));
        BufferedReader buf = new BufferedReader(reader);
        String line;
        while ((line = buf.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }

    private static void fileInputStreamForRead(String filename) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(filename);
        byte[] bytes = new byte[1024];
        String content = "";
        while (fileInputStream.read(bytes) > 0) {
            content += new String(bytes, getFileCodeType(filename));
        }
        System.out.println(content);
        fileInputStream.close();
    }


}
